package io.yunho.srw.lean.webflux;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author: Jason
 * @date: 2021/5/12 9:09
 * @description:
 */
public class AsyncServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        long t1 = System.currentTimeMillis();
        //开启异步
        AsyncContext asyncContext = req.startAsync();
        //执行业务代码
        CompletableFuture.runAsync(()-> {
            try {
                dosomething(asyncContext,(HttpServletResponse) asyncContext.getResponse());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        System.out.println("sycn_use:"+(System.currentTimeMillis()-t1));
    }

    private void dosomething(AsyncContext asyncContext, HttpServletResponse resp) throws IOException {
        try {
            TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}
        System.out.println("sync_use");
        resp.getWriter().append("haha ");
        //通知上下文 执行结束
        asyncContext.complete();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
